#include "NewSimulationDialog.h"

#include <imgui.h>

#include <Base/GlobalSettings.h>

#include <EngineInterface/SimulationFacade.h>

#include "AlienGui.h"
#include "StyleRepository.h"
#include "TemporalControlWindow.h"
#include "Viewport.h"
#include <EngineInterface/SimulationFacade.h>

namespace
{
    auto const ContentTextInputWidth = 130.0f;
    auto const ProjectNameSize = sizeof(Char64) / sizeof(char);
}

void NewSimulationDialog::initIntern()
{

    _adoptSimulationParameters = GlobalSettings::get().getValue("dialogs.new simulation.adopt simulation parameters", true);
}

void NewSimulationDialog::shutdownIntern()
{
    GlobalSettings::get().setValue("dialogs.new simulation.adopt simulation parameters", _adoptSimulationParameters);
}

NewSimulationDialog::NewSimulationDialog()
    : AlienDialog("New simulation")
{}

void NewSimulationDialog::processIntern()
{
    AlienGui::InputText(AlienGui::InputTextParameters().name("Project name").textWidth(ContentTextInputWidth), _projectName, ProjectNameSize);
    AlienGui::InputInt(AlienGui::InputIntParameters().name("Width").textWidth(ContentTextInputWidth), _width);
    AlienGui::InputInt(AlienGui::InputIntParameters().name("Height").textWidth(ContentTextInputWidth), _height);
    AlienGui::Checkbox(AlienGui::CheckboxParameters().name("Adopt parameters").textWidth(ContentTextInputWidth), _adoptSimulationParameters);

    ImGui::Dummy({0, ImGui::GetContentRegionAvail().y - scale(50.0f)});
    AlienGui::Separator();
    if (AlienGui::Button("OK")) {
        ImGui::CloseCurrentPopup();
        onNewSimulation();
        close();
    }
    ImGui::SetItemDefaultFocus();

    ImGui::SameLine();
    if (AlienGui::Button("Cancel")) {
        ImGui::CloseCurrentPopup();
        close();
    }

    _width = std::max(1, _width);
    _height = std::max(1, _height);
}

void NewSimulationDialog::openIntern()
{
    auto worldSize = _SimulationFacade::get()->getWorldSize();
    _width = worldSize.x;
    _height = worldSize.y;
}

void NewSimulationDialog::onNewSimulation()
{
    SimulationParameters parameters;
    if (_adoptSimulationParameters) {
        parameters = _SimulationFacade::get()->getSimulationParameters();
    }
    for (int i = 0; i < ProjectNameSize; ++i) {
        parameters.projectName.value[i] = _projectName[i];
    }
    _SimulationFacade::get()->closeSimulation();

    _SimulationFacade::get()->newSimulation(0, {_width, _height}, parameters);
    Viewport::get().setCenterInWorldPos({toFloat(_width) / 2, toFloat(_height) / 2});
    Viewport::get().setZoomFactor(4.0f);
    TemporalControlWindow::get().onSnapshot();
}
